using System.Data;
using System.Web.UI.WebControls;
using System;
using StillVoiceCommon;
using TeamTime.Classes;
namespace TeamTime
{

    partial class UsersForm : System.Web.UI.Page
    {
        Security sec;

        //Dim adap As New SqlDataAdapter(sql, conn) 
        //int UserGroupID = 0; 
        bool isEditing = false;
        #region " Web Form Designer Generated Code "

        //This call is required by the Web Form Designer. 
        [System.Diagnostics.DebuggerStepThrough()]
        private void InitializeComponent()
        {

        }

        protected System.Web.UI.WebControls.Label msg;
        protected System.Web.UI.WebControls.DropDownList ddlSecurityItem;
        protected System.Web.UI.WebControls.DropDownList ddlUserGroup;

        protected DataSet dsUserGroups = new DataSet();
        protected DataSet dsGrid = new DataSet();


        private void Page_Init(object sender, System.EventArgs e)
        {
            InitializeComponent();
            sec = new Security(sqlDB.getDBConnString());
            dsUserGroups = sec.GetUserGroups(false);
        }

        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //TopMenu1.checkPagePermissions = true; 
                //TopMenu1.pagePermissionsMsg = "You do not have rights to manage Users"; 
                Functions.dropDownListPopulate(this.ddlUserGroups, sec.GetUserGroups(true), "ID", "UserGroup");
                BindGrid(false,"");
            }

            //if ((bool)Session["UserIsReadOnly"]) { 
            //    LinkButton1.Enabled = false; 
            //} 
        }

        // --------------------------------------------------------------- 
        // DataGrid Commands: Page, Sort, Edit, Update, Cancel, Delete 
        // 
        public void DataGrid_ItemCommand(object Sender, DataGridCommandEventArgs E)
        {
            // this event fires prior to all of the other commands 

            //if ((bool)Session["UserIsReadOnly"]) { 
            //    Message.Text = "You cannot edit anything, Your permissions are read only."; 
            //    return; // TODO: might not be correct. Was : Exit Sub 
            //} 
            CheckIsEditing(E.CommandName);
            if (E.CommandName == "ResetPassword")
            {
                string id = DataGrid1.DataKeys[E.Item.ItemIndex].ToString();
                StillVoiceCommon.User u = new StillVoiceCommon.User(Convert.ToInt32(Session["UserID"]));
                u.load(id, "ID");
                u.resetPassword();
                this.LabelWithTimedMsg1.ShowStatusMessage("Password successfully reset", 3);
                try
                {
                    u.sendPasswordEmail(Request.ServerVariables["SERVER_NAME"], Request.ServerVariables["SERVER_PORT"]);
                }
                catch { }
                u = null;
            }
        }

        public void CheckIsEditing(string commandName)
        {
            if (DataGrid1.EditItemIndex != -1)
            {
                // we are currently editing a row 
                if (commandName != "Cancel" & commandName != "Update")
                {
                    // user's edit changes (If any) will not be committed 
                    Message.Text = "Your changes have not been saved yet. Please press update to save your changes, or cancel to discard your changes, before selecting another item.";
                    isEditing = true;
                }
            }
        }
        // 
        // turn on editing for the selected row 
        public void DataGrid_Edit(object Sender, DataGridCommandEventArgs E)
        {
            //if ((bool)Session["UserIsReadOnly"]) { 
            //    Message.Text = "You cannot edit anything, Your permissions are read only."; 
            //    return; // TODO: might not be correct. Was : Exit Sub 
            //} 
            if (!isEditing)
            {
                DataGrid1.EditItemIndex = E.Item.ItemIndex;
                BindGrid(false,"");
            }
        }

        // update the database with the new values 
        public void DataGrid_Update(object Sender, DataGridCommandEventArgs e)
        {

            //if ((bool)Session["UserIsReadOnly"]) { 
            //    Message.Text = "You cannot edit anything, Your permissions are read only."; 
            //    return; // TODO: might not be correct. Was : Exit Sub 
            //} 
            TableCellCollection RowCells;
            RowCells = e.Item.Cells;

            string id = DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
            //CType(RowCells[1).FindControl("txtUserID"), TextBox).Text 
            StillVoiceCommon.User u = new StillVoiceCommon.User(Convert.ToInt32(Session["UserID"]));
            if (id != "0")
                u.load(id, "ID");
            else
                u.setForAdd();

            {
                // .Fields["UserID"] = CType(RowCells[1).FindControl("ddlUserID"), DropDownList).SelectedValue 
                u.Fields["LastName"] = ((TextBox)RowCells[1].FindControl("txtLastName")).Text;
                u.Fields["FirstName"] = ((TextBox)RowCells[2].FindControl("txtFirstName")).Text;
                u.Fields["LoginCode"] = ((TextBox)RowCells[3].FindControl("txtLoginCode")).Text;
                //.Fields["Password"] = CType(RowCells[4).FindControl("txtPassword"), TextBox).Text 
                if (AddingNew)
                    u.Fields["Password"] = "password";
                u.Fields["DefaultUserGroupID"] = ((DropDownList)RowCells[5].FindControl("ddlDefaultUserGroupID")).SelectedValue;
                if (((TextBox)RowCells[6].FindControl("txtStandardHourlyRate")).Text != "")
                    u.Fields["StandardHourlyRate"] = ((TextBox)RowCells[6].FindControl("txtStandardHourlyRate")).Text;
                u.Fields["Email"] = ((TextBox)RowCells[7].FindControl("txtEmail")).Text;
                if (((TextBox)RowCells[8].FindControl("txtInactiveDate")).Text != "")
                    u.Fields["InactiveDate"] = ((TextBox)RowCells[8].FindControl("txtInactiveDate")).Text;
                u.Fields["ReadOnly"] = 0;//CType(RowCells[9).FindControl("chkreadOnly"), CheckBox).Checked 

                u.updateWithUserIDDate();
                u.addUserToDefaultGroup();
                //ensure that the user is a member of their default group 
            }
            // Resort the grid for new records 
            if (AddingNew == true)
            {
                DataGrid1.CurrentPageIndex = 0;
                AddingNew = false;
            }

            // rebind the grid 
            DataGrid1.EditItemIndex = -1;
            BindGrid(false,"");
            u = null;
        }

        // cancel editing 
        public void DataGrid_Cancel(object Sender, DataGridCommandEventArgs E)
        {
            DataGrid1.EditItemIndex = -1;
            DataGrid1.CurrentPageIndex = 0;
            BindGrid(false,"");
            AddingNew = false;
        }

        //Sub DataGrid_Delete(ByVal Sender As Object, ByVal E As DataGridCommandEventArgs) 

        // delete the selected row 
        // If Not isEditing Then 
        // the key value for this row is in the DataKeys collection 
        // Dim keyValue As String = CStr(DataGrid1.DataKeys(E.Item.ItemIndex)) 
        // sqlDB.execSQL("DELETE from [Security].[User] where UserID=" & keyValue) 

        // rebind the grid 
        // DataGrid1.CurrentPageIndex = 0 
        // DataGrid1.EditItemIndex = -1 
        // BindGrid() 
        // End If 
        //End Sub 

        public void DataGrid_Page(object Sender, DataGridPageChangedEventArgs E)
        {
            // display a new page of data 
            if (!isEditing)
            {
                DataGrid1.EditItemIndex = -1;
                DataGrid1.CurrentPageIndex = E.NewPageIndex;
                BindGrid(false, "");
            }
        }
        // 
        // add a new row to the end of the data, and set editing mode 'on' 
        public void AddNew_Click(object Sender, EventArgs E)
        {

            //if ((bool)Session["UserIsReadOnly"]) { 
            //    Message.Text = "You cannot edit anything, Your permissions are read only."; 
            //    return; // TODO: might not be correct. Was : Exit Sub 
            //} 
            CheckIsEditing("");
            if (!(isEditing == true))
            {
                AddingNew = true;
                //set the flag so we know to do an insert at Update time 
                BindGrid(true, "");
                // add a new blank row to the end of the data 

                //UserID, [User Name], LastName, FirstName, Email, InactiveDate, LoginCode, Password, DefaultUserGroupID, StandardHourlyRate, ReadOnly 
                object[] rowValues = {0, "", "", "", DBNull.Value, DBNull.Value, "", "", 10, DBNull.Value, 
                0};
                //, False} '10 is the Default 'Users' group 
                dsGrid.Tables[0].Rows.Add(rowValues);

                // figure out the EditItemIndex, last record on last page 
                int recordCount = dsGrid.Tables[0].Rows.Count;
                if (recordCount > 1)
                {
                    recordCount -= 1;
                    DataGrid1.CurrentPageIndex = recordCount / DataGrid1.PageSize;
                    DataGrid1.EditItemIndex = recordCount % DataGrid1.PageSize;
                }
                else
                {
                    DataGrid1.EditItemIndex = 0;
                }
                // databind 
                DataGrid1.DataSource = dsGrid;
                DataGrid1.DataBind();
            }
        }

        // --------------------------------------------------------------- 
        // 
        // Helper Methods: 
        // 

        // property to keep track of whether we are adding a new record, 
        // and save it in viewstate between postbacks 
        public bool AddingNew
        {
            get
            {
                object o = ViewState["AddingNew"];
                if (o == null)
                {
                    return false;
                }
                return (bool)o;
            }

            set { ViewState["AddingNew"] = value; }
        }

        public void BindGrid(bool AddNew, string orderBy)
        {
            //UserGroupID = ddUserGroups.SelectedValue ' Functions.SelectedRecID(dsUsers, ddUserGroups.SelectedIndex) 
            if (orderBy == null) orderBy = "";
            if (orderBy == "" && DataGrid1.Attributes["orderBy"] != null)
                orderBy = DataGrid1.Attributes["orderBy"];
            dsGrid = sec.getUsers(Convert.ToInt32(ddlUserGroups.SelectedValue), orderBy, false, false);
            DataGrid1.DataSource = dsGrid;
            DataGrid1.DataBind();
        }
        //Sub BindGrid(Optional ByVal AddNew As Boolean = False) 
        // 'UserGroupID = ddUserGroups.SelectedValue ' Functions.SelectedRecID(dsUsers, ddUserGroups.SelectedIndex) 
        // dsGrid = TopMenu1.sec.getUsers(Me.ddlUserGroups.SelectedValue) 

        // If AddNew Then 
        // ' add a new blank row to the end of the data 
        // 'UserID, LastName, FirstName, LoginCode, Password, DefaultUserGroupID, StandardHourlyRate, Email, InactiveDate 
        // Dim rowValues As Object() = {0, "", "", "", "", 0, "", "", ""} 
        // dsGrid.Tables[0].Rows.Add(rowValues) 
        // End If 
        // DataGrid1.DataSource = dsGrid 
        // DataGrid1.DataBind() 
        //End Sub 

        protected void ddlUserGroups_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            BindGrid(false, DataGrid1.Attributes["orderBy"]);
        }

        protected void DataGrid1_SortCommand(object source, DataGridSortCommandEventArgs e)
        {
            DataGrid1.Attributes.Add("orderBy", e.SortExpression);
            BindGrid(false, e.SortExpression);
        }


    }

}